<%@ page language="java" pageEncoding="UTF-8"
%><%@ page contentType="image/jpeg"
%><%@ page import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"
%><%! 
Color getRandColor(int fc,int bc){//给定范围获得随机颜色 
Random random = new Random(); 
if(fc>255) fc=255; 
if(bc>255) bc=255; 
int r=fc+random.nextInt(bc-fc); 
int g=fc+random.nextInt(bc-fc); 
int b=fc+random.nextInt(bc-fc); 
return new Color(r,g,b); 
} 
%><% 
//设置页面不缓存 
response.setHeader("Pragma","No-cache"); 
response.setHeader("Cache-Control","no-cache"); 
response.setDateHeader("Expires", 0); 

// 在内存中创建图象 
int width=70, height=20; 
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 

// 获取图形上下文 
Graphics g = image.getGraphics(); 

//生成随机类 
Random random = new Random(); 

// 设定背景色 
g.setColor(getRandColor(200,250)); 
g.fillRect(0, 0, width, height); 
//String [] fontname={"黑体","宋体","方正姚体","黑体"};
String [] fontname={"黑体","黑体","黑体","黑体"};

//画边框 
//g.setColor(new Color()); 
//g.drawRect(0,0,width-1,height-1); 

// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到 
g.setColor(getRandColor(160,200)); 
for (int i=0;i<15;i++) 
{ 
int x = random.nextInt(width); 
int y = random.nextInt(height); 
int xl = random.nextInt(12); 
int yl = random.nextInt(12); 
g.drawLine(x,y,x+xl,y+yl); 
} 

// 取随机产生的认证码(三个汉字) 
String sRand=""; 
//String charstr="一地在要工上是中国同和的有人我主产不为这民了发以经到天表于五下不理事画现与来列平珍玉地支城寺二直示进吉协志赤过无才增雪夫左友大胡夺三丰砂百右历面成灰达克原厅帮磁春龙太李权枯村本相档查可机杨杰林样要检术式节芭基七牙东划或功贡世区攻燕切共药芳虎皮肯睛止步旧占贞卢眯睡眼具此眩虹最紧晨明时量早晃昌蝇遇电显晕晚果昨暗归蛤昆景呀啊吧顺吸叶呈中吵虽吕另员叫史听呆啼哪只哟嘛轼轻因胃轩车四加男轴思边罗斩困力较轨办累罚曲邮凤央骨财同由峭则册岂迪风朵几赠内凡长季么知秀行生处秒得各务向秘秋管称物条笔科委答第入找报反拓扔持后年朱提扣押抽所搂近换折打手拉扫失批扩服肥须朋肝且胩膛胆肿肋肌甩采用脸脂及代他公估仍会全个偿介保仙亿伙你伯休作们分从化信色然角针钱外乐旬名甸负包多铁钉儿匀争欠久度离充庆衣计主让就是训为高记变这义诉订放说良认率方闻冯关前半闰站冰间部曾商决普帝交亲产立妆闪北六江池汉尖肖法汪小水浊澡渐没沁淡学光泊洒少洋当兴涨注煤类粗灶业粘炒烛炽烟断炎迷灯料粉米宽字害家守定寂宵审宫军宙官灾之宾宁客实空它社";
String charstr="0123456789";
int indexstr=0;
for(int i=0;i<4;i++){ 
//设定字体 
indexstr = random.nextInt(100)%10;
//g.setFont(new Font(fontname[indexstr%4],indexstr%2,indexstr>50?22:16)); 
g.setFont(new Font(fontname[indexstr%4],1,22)); 
String rand=charstr.substring(indexstr,indexstr+1); 
sRand+=rand;  
//将认证码显示到图象中  
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))); 
//调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成 
g.drawString(rand,18*i+2,16); 
} 
// 将认证码存入SESSION 
session.setAttribute("rand",sRand); 

// 图象生效 
g.dispose(); 

// 输出图象到页面 
ImageIO.write(image, "JPEG", response.getOutputStream()); 
%>